package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import com.itheima.utils.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.UUID;
//套餐管理
@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Reference
    private SetmealService setmealService;
    @Autowired
    private JedisPool jedisPool;
    @RequestMapping("/upload")
    public Result upload(@RequestParam("imgFile")MultipartFile imgFile){
        String originalFilename = imgFile.getOriginalFilename();//获得文件名
        int index = originalFilename.lastIndexOf(".");//获取文件中最后一个.的索引，比如abc.jpg
        String substring = originalFilename.substring(index - 1);//获取文件的后缀名 .jpg等等   -1是为了把.也截取进去
        //为了保证存入七牛云中的文件名唯一，采用uuid加文件后缀的方式作为存入的文件名
        String fileName = UUID.randomUUID().toString()+substring;
        //调用工具类中的方法，把接收到的文件上传到七牛云
        try {
            QiniuUtils.upload2Qiniu(imgFile.getBytes(),fileName);
            /*将存入七牛云的图片名称存入jedis的map集合中*/
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES,fileName);
            //上传成功，将七牛云中存储的文件名响应到前台，用于预览
            return new Result(true,MessageConstant.PIC_UPLOAD_SUCCESS,fileName);
        } catch (IOException e) {
            e.printStackTrace();
            //上传失败
            return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);
        }
    }
    @RequestMapping("/add")
    public Result add(@RequestBody Setmeal setmeal,Integer[] checkgroupIds){
        try {
            setmealService.add(setmeal,checkgroupIds);

        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.ADD_SETMEAL_FAIL);
        }
        return new Result(true,MessageConstant.ADD_SETMEAL_SUCCESS);
    }
    @RequestMapping("/findPage")
    public PageResult findPage( @RequestBody QueryPageBean queryPageBean){
        return setmealService.findPage(queryPageBean);
    }
}
